<template>
  <div id="eqMaintainPlanDiv">
    <Breadcrumb content="保养计划" />
    <div class="bodyContent">
      <Splitpanes horizontal class="horizontalLine">
        <Pane size="100">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findMaintainPlanList" @keyup="keyupEnter" @search-click="findMaintainPlanList()"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="查询" :loading="tloading" @click="findMaintainPlanList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="添加计划" @click="addMaintainPlanDialog()"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-check" content="启用" @click="handleStopStart('10')"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-minus" content="停用" @click="handleStopStart('4')"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteBatchMaintainPlan"></vxe-button>

              &nbsp;&nbsp;&nbsp;&nbsp;
              <div class="tag-group">
                <span class="tag-group__title">【状态】：</span>
                <el-tag size="mini" v-for="item in planStatusList.filter((a)=>a.code!='0')" :key="item.code" :type="getTagTypeSear(item)" effect="plain" :class="searchForm.planStatus==item.code?'selectedElTagClazz':'elTagClazz'" @click="clickPlanStatus(item)">
                  {{ item.name }}
                </el-tag>
              </div>
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <vxe-table ref="maintainPlanTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="maintainPlanList" :loading="tloading" @current-change="maintainPlanRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="seq" width="30" title=""></vxe-column>
              <vxe-column type="checkbox" width="30"></vxe-column>
              <vxe-column title="操作" align="center" width="150">
                <template #default="{ row }">
                  <el-link type="primary" :underline="false" @click="executeMaintainPlan(row)" class="el-link_clazz">
                    <span>执行计划</span>
                  </el-link>
                  <el-link type="primary" :underline="false" @click="maintainPlanRecords(row)">
                    <span>相关记录</span>
                  </el-link>
                </template>
              </vxe-column>
              <vxe-column field="planNo" title="计划编号" width="150">
                <template #default="{ row }">
                  <el-link type="primary" :underline="false" @click="EditMaintainPlan(row)">
                    <span> {{ row.planNo}}</span>
                  </el-link>
                </template>
              </vxe-column>
              <vxe-column field="planStatus" title="状态" width="80">
                <template #default="{ row }">
                  <div class="flex justify-atart">
                    <span :class="getStatusClass(row)" style="margin-right: 2px;">
                      {{ formatCommon(planStatusList, row.planStatus) }}
                    </span>
                  </div>
                </template>
              </vxe-column>
              <vxe-column field="equiptCode" title="设备编码" width="100">
              </vxe-column>
              <vxe-column field="equiptName" title="设备名称" width="100">
              </vxe-column>
              <vxe-column field="specification" title="设备型号" width="150">
              </vxe-column>
              <vxe-column field="maintainType" title="保养类型" width="150">
                <template #default="{ row }">
                  <span>{{ formatCommon(maintainTypeList, row.maintainType) }}</span>
                </template>
              </vxe-column>

              <vxe-column field="planType" title="计划类型" width="80">
                <template #default="{ row }">
                  {{ formatPlanType( row) }}
                </template>
              </vxe-column>
              <vxe-column field="nextDate" title="下次保养时间" width="150">
              </vxe-column>
              <vxe-column field="startDate" title="计划开始时间" width="150">
              </vxe-column>
              <vxe-column field="endDate" title="计划结束时间" width="150">
              </vxe-column>
              <vxe-column field="remark" title="说明">
                <template #default="{ row }">
                  <span>{{ row.remark }}</span>
                </template>
              </vxe-column>

            </vxe-table>
            <vxe-pager align="left" min-height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="[
                'PrevJump',
                'PrevPage',
                'Number',
                'NextPage',
                'NextJump',
                'Sizes',
                'FullJump',
                'Total'
              ]" @page-change="handleSizeChange($event)"></vxe-pager>
          </div>
        </Pane>
      </Splitpanes>
    </div>

  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import moment from 'moment';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
let { proxy }: any = getCurrentInstance();
import { AppStore } from '@/stores/store'; //'../../../stores/store';
import { isEmpty } from 'lodash';

// 全局变量定义区 ==========
let searchForm = {
  searchValue: '',
  planStatus: ''
};
let tloading = ref(false); //加载状态
let maintainPlanList: any = reactive([]);
let planStatusList: any = reactive([]); //选择字典
let maintainTypeList: any = reactive([]);
let sltMainlan: any = ref({});

let planTypeList: any = reactive([
  { name: '单次', code: '1' },
  { name: '多次', code: '2' }
]); //选择字典
// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  if (!isEmpty(proxy.$route.query.pageSize)) {
    page.pageSize = parseInt(proxy.$route.query.pageSize.toString(), 10);
  }
  if (!isEmpty(proxy.$route.query.pageIndex)) {
    page.currentPage = parseInt(proxy.$route.query.pageIndex.toString(), 10);
  }

  if (!isEmpty(proxy.$route.query.planId)) {
    sltMainlan.value.id = proxy.$route.query.planId.toString();
  }
  getDictItemsList(); //批量获取字典
  findMaintainPlanList();
});

function clickPlanStatus(row: any) {
  if (searchForm.planStatus == row.code) {
    searchForm.planStatus = '';
  } else {
    searchForm.planStatus = row.code;
  }
  findMaintainPlanList();
}

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['maintainType', 'planStatus'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const maintainTypes = dictTreeTypeItems.data.find((item: any) => item.code === 'maintainType');
  maintainTypeList.push(...maintainTypes.detailDataList);
  const planStatues = dictTreeTypeItems.data.find((item: any) => item.code === 'planStatus');
  planStatusList.push(...planStatues.detailDataList);
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findMaintainPlanList();
  }
}

//点击每页数量(分页查询)
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findMaintainPlanList();
}

function findMaintainPlanList() {
  tloading.value = true;
  maintainPlanList.length = 0; //放入数据前清空数据
  const url = '/api/eq/eqMaintainPlan/findMaintainPlanPageList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchForm.searchValue,
        status: searchForm.planStatus,
        pageIndex: page.currentPage,
        pageSize: page.pageSize
      }
    })
    .then((res: any) => {
      maintainPlanList.push(...res.data.records);
      page.totalResult = res.data.total;

      const kn = maintainPlanList.find((k: any) => k.id == sltMainlan.value.id);
      if (isEmpty(kn)) {
        maintainPlanRowClick({ row: maintainPlanList[0] }); //默认选中第一条数据
      } else {
        maintainPlanRowClick({ row: kn }); //默认选中第一条数据
      }

      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}
function maintainPlanRowClick({ row }: any) {
  if (isEmpty(row)) {
    sltMainlan.value = {};
    maintainPlanList.length = 0; //放入数据前清空数据
  } else {
    (proxy.$refs.maintainPlanTableRef as any).setCurrentRow(row);
    sltMainlan.value = row;
  }
}

function addMaintainPlanDialog() {
  const data = {
    pageIndex: page.currentPage.toString(),
    pageSize: page.pageSize.toString(),
    url: '/eqMaintainPlan'
  };
  proxy.$router.push({ path: '/eqMaintainPlanEdit', query: data });
}

function executeMaintainPlan(row: any) {
  const data = {
    planId: row.id,
    pageIndex: page.currentPage.toString(),
    pageSize: page.pageSize.toString(),
    url: '/eqMaintainPlan'
  };
  proxy.$router.push({ path: '/eqMaintainEdit', query: data });
}
function maintainPlanRecords(row: any) {
  //eqMaintainOrder
  const data = {
    planId: row.id,
    pageIndex: page.currentPage.toString(),
    pageSize: page.pageSize.toString(),
    url: '/eqMaintainPlan',
    xgjlUrl: '/eqMaintainPlan'
  };
  proxy.$router.push({ path: '/eqMaintainOrder', query: data });
}

function EditMaintainPlan(row: any) {
  const data = {
    id: row.id,
    pageIndex: page.currentPage.toString(),
    pageSize: page.pageSize.toString(),
    url: '/eqMaintainPlan'
  };
  proxy.$router.push({ path: '/eqMaintainPlanEdit', query: data });
}

function deleteBatchMaintainPlan() {
  const sltMaintainPlans = (proxy.$refs.maintainPlanTableRef as any).getCheckboxRecords();
  if (!(sltMaintainPlans.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delMaintainPlanList = sltMaintainPlans.filter((p: any) => !isEmpty(p.id));
        if (delMaintainPlanList.length > 0) {
          const data = { eqMaintainPlanList: delMaintainPlanList };
          const url = '/api/eq/eqMaintainPlan/batchDeleteMaintainPlanList';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findMaintainPlanList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function handleStopStart(planStatus: any) {
  const sltMaintainPlans = (proxy.$refs.maintainPlanTableRef as any).getCheckboxRecords();

  if (!(sltMaintainPlans.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    let isSopStar = true;
    for (const sltMaintain of sltMaintainPlans) {
      if (planStatus == '10') {
        if (!(sltMaintain.planStatus == '4')) {
          isSopStar = false;
        }
      } else if (planStatus == '4') {
        if (!(sltMaintain.planStatus == '5' || sltMaintain.planStatus == '10')) {
          isSopStar = false;
        }
      } else {
        isSopStar = false;
      }
    }
    if (!isSopStar) {
      VxeMessage('计划状态不符,请重试', VxeNotifyType.error);
      return;
    }
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delMaintainPlanList = sltMaintainPlans.filter((p: any) => !isEmpty(p.id));
        if (delMaintainPlanList.length > 0) {
          const data = { eqMaintainPlanList: delMaintainPlanList, planStatus: planStatus };
          const url = '/api/eq/eqMaintainPlan/batchMaintainPlanStopStart';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findMaintainPlanList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function getStatusClass(row: any) {
  const status = row.planStatus;
  if (status == '0') {
    return 'text-orange';
  } else if (status == '5') {
    return 'text-orange';
  } else if (status == '4') {
    return 'text-blue';
  } else if (status == '10') {
    return 'text-green';
  } else if (status == '99') {
    return 'text-black';
  }
}

function getTagTypeSear(row: any) {
  const status = row.code;
  if (status == '0') {
    return 'warning';
  } else if (status == '5') {
    return 'warning';
  } else if (status == '4') {
    return 'primary';
  } else if (status == '10') {
    return 'success';
  } else if (status == '99') {
    return 'info';
  }
}

function formatCommon(arr: any, value: any) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
function formatPlanType(row: any) {
  for (const item of planTypeList) {
    if (item.code == row.planType) {
      return item.name;
    }
  }
}
</script>

<style lang="scss" scoped>
#eqMaintainPlanDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
    }
    .horizontalLine {
      :deep(.splitpanes__splitter) {
        background-color: $base-white;
      }
    }

    // 中间table表格
    .tableBody {
      height: calc(100% - 40px - 32px);
    }
    // 质控靶值设定弹框表格
    .tableTargetBody {
      height: 600px;
      .tableTargetBodyRight {
        height: calc(100% - 2px);
        border: 1px solid #e8eaec;

        .closeBtn {
          margin-left: 720px;
        }
      }
    }

    // 右侧保存按钮
    .saveBtn {
      float: right;
      margin: 5px 10px;
    }
    .el-form {
      padding-right: 15px;
      .el-form-item--large {
        margin-bottom: 10px;
      }
      .el-button {
        padding: 5px 2px !important;
      }
      :deep(.el-input__inner) {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }

    // 弹框
    .el-dialog {
      font-weight: 700;
      max-height: 1000px;
      padding: 10px;
    }
    // 最右侧质控项目设定表格
    .tableBox {
      height: calc(100% - 40px);
    }
    .el-link_clazz {
      margin-right: 5px;
    }
    .elTagClazz {
      margin-left: 5px;
      cursor: pointer;
    }
    .selectedElTagClazz {
      margin-left: 5px;
      cursor: pointer;
      background-color: #89d7fc;
    }
  }
}
</style>